import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import pandas as pd
import threading
import os
import sys
import time

class TrackingTab(ttk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.file_path = None
        self.df = None
        self.selected_column = tk.StringVar()
        self.query_values = []
        self.query_values_all = []
        # 先定义状态和进度变量，避免AttributeError
        self.status_var = tk.StringVar(value="等待操作")
        self.total_count = 0
        self.preview_count = 0
        self.proc = None  # 保存子进程对象
        self.is_running = False
        self.is_paused = False
        self.last_selected_category = None  # 记录上次选中的分类
        self.create_widgets()

    def create_widgets(self):
        # 让整个Tab自适应拉伸
        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(0, weight=1)
        # 顶部一行：上传Excel+选择查询字段+开始查询
        top_frame = ttk.Frame(self)
        top_frame.grid(row=0, column=0, columnspan=2, sticky='we', padx=5, pady=5)
        self.upload_btn = ttk.Button(top_frame, text="上传Excel", command=self.upload_excel)
        self.upload_btn.pack(side=tk.LEFT, padx=(0, 10))
        self.file_name_label = ttk.Label(top_frame, text="", foreground="#333")
        self.file_name_label.pack(side=tk.LEFT, padx=(5,0))
        self.header_label = ttk.Label(top_frame, text="选择查询字段：")
        self.header_label.pack(side=tk.LEFT)
        self.header_combo = ttk.Combobox(top_frame, textvariable=self.selected_column, state='readonly')
        self.header_combo.pack(side=tk.LEFT, padx=(5, 0))
        self.header_combo.bind('<<ComboboxSelected>>', self.on_column_selected)
        # "开始查询"按钮放到最右侧
        self.query_btn = ttk.Button(top_frame, text="开始查询", command=self.on_query_btn_click, state='disabled', width=12)
        self.query_btn.pack(side=tk.RIGHT, padx=(10,0))
        

        # 中部：左侧查询条件预览，右侧输出文件夹统计
        mid_frame = ttk.Frame(self, height=250)
        mid_frame.grid(row=1, column=0, columnspan=2, sticky='nsew', padx=5, pady=5)
        mid_frame.grid_propagate(False)
        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(0, weight=1)
        mid_frame.grid_rowconfigure(0, weight=1)
        mid_frame.grid_columnconfigure(0, weight=3)
        mid_frame.grid_columnconfigure(1, weight=7)
        # 左侧查询条件预览
        preview_frame = ttk.Frame(mid_frame, width=220, height=250)
        preview_frame.grid(row=0, column=0, sticky='nsew')
        preview_frame.grid_propagate(False)
        preview_frame.grid_rowconfigure(1, weight=1)
        preview_frame.grid_columnconfigure(0, weight=1)
        label_frame = ttk.Frame(preview_frame)
        label_frame.grid(row=0, column=0, sticky='w')
        self.preview_label = ttk.Label(label_frame, text="查询条件预览：")
        self.preview_label.pack(side=tk.LEFT)
        self.count_label = ttk.Label(label_frame, text="共0条")
        self.count_label.pack(side=tk.LEFT, padx=(10,0))
        self.preview_text = tk.Text(preview_frame, height=8, width=20, state='disabled')
        self.preview_text.grid(row=1, column=0, sticky='nsew')
        # 右侧输出文件夹统计
        self.output_frame = ttk.LabelFrame(mid_frame, text="输出文件夹统计")
        self.output_frame.grid(row=0, column=1, sticky='nsew', padx=(10,0))
        self.output_frame.grid_rowconfigure(0, weight=1)
        self.output_frame.grid_columnconfigure(0, weight=1)
        self.output_frame.grid_columnconfigure(1, weight=1)
        self.category_listbox = tk.Listbox(self.output_frame, selectmode=tk.SINGLE, height=8)
        self.category_listbox.grid(row=0, column=0, sticky='nswe', padx=(0,5), pady=2)
        self.category_listbox.bind('<<ListboxSelect>>', self.on_category_select)
        self.file_listbox = tk.Listbox(self.output_frame, selectmode=tk.SINGLE, height=8)
        self.file_listbox.grid(row=0, column=1, sticky='nswe', padx=(5,0), pady=2)
        bottom_frame = ttk.Frame(self.output_frame)
        bottom_frame.grid(row=1, column=0, columnspan=2, sticky='we')
        self.total_label = ttk.Label(bottom_frame, text="总图片数: 0")
        self.total_label.pack(side=tk.LEFT, padx=5)
        self.open_folder_btn = ttk.Button(bottom_frame, text="打开文件夹位置", command=self.open_output_folder)
        self.open_folder_btn.pack(side=tk.RIGHT, padx=5)
        self.output_stats = {}
        self.refresh_output_stats()
        self.after(1000, self.auto_refresh_output_stats)

        # 底部：状态栏+停止查询按钮+工作日志
        status_frame = ttk.Frame(self)
        status_frame.grid(row=2, column=0, columnspan=2, sticky='we', padx=5, pady=5)
        self.status_label = ttk.Label(status_frame, textvariable=self.status_var, anchor='w')
        self.status_label.pack(side=tk.LEFT, fill=tk.X, expand=True)
        # 工作日志区只显示最新一条
        log_frame = ttk.LabelFrame(self, text="工作日志")
        log_frame.grid(row=3, column=0, columnspan=2, sticky='we', padx=5, pady=5)
        self.log_text = tk.Text(log_frame, height=3, state='disabled')
        self.log_text.pack(fill=tk.BOTH, expand=True)
        # 状态
        self.is_running = False
        self.is_paused = False
        self.proc = None

    def auto_refresh_output_stats(self):
        self.refresh_output_stats()
        self.after(1000, self.auto_refresh_output_stats)

    def upload_excel(self):
        file_path = filedialog.askopenfilename(filetypes=[('Excel Files', '*.xlsx'), ('Excel Files', '*.xls')])
        if not file_path:
            return
        try:
            df = pd.read_excel(file_path)
            self.df = df
            self.file_path = file_path
            self.header_combo['values'] = list(df.columns)
            
            if len(df.columns) >= 2:
                self.selected_column.set(df.columns[1])
                # 500毫秒后执行on_column_selected
                self.after(500, self.on_column_selected)
            elif len(df.columns) == 1:
                self.selected_column.set(df.columns[0])
                self.after(500, self.on_column_selected)
            else:
                self.selected_column.set('')
                self.after(500, self.on_column_selected)
            self.query_btn['state'] = 'disabled'
            self.preview_text['state'] = 'normal'
            self.preview_text.delete('1.0', tk.END)
            self.preview_text['state'] = 'disabled'
            self.count_label['text'] = "共0条"
            # 显示文件名
            self.file_name_label['text'] = os.path.basename(file_path)
            
        except Exception as e:
            messagebox.showerror('错误', f'读取Excel失败：{e}')

    def on_column_selected(self, event=None):
        col = self.selected_column.get()
        if self.df is not None and col:
            values = self.df[col].dropna().astype(str).unique().tolist()
            self.query_values_all = values  # 保存全部单号
            self.total_count = len(values)
            self.preview_count = min(100, self.total_count)
            self.preview_text['state'] = 'normal'
            self.preview_text.delete('1.0', tk.END)
            self.preview_text.insert(tk.END, '\n'.join(values[:100]))  # 只预览前100个
            self.preview_text['state'] = 'disabled'
            self.count_label['text'] = f"共{self.total_count}条，预览{self.preview_count}条"
            self.query_btn['state'] = 'normal' if values else 'disabled'
        else:
            self.query_btn['state'] = 'disabled'
            self.count_label['text'] = "共0条"

    def on_query_btn_click(self):
        if self.query_btn['text'] == '开始查询':
            self.start_query()
        elif self.query_btn['text'] == '停止查询':
            self.stop_query()

    def start_query(self):
        if not hasattr(self, 'query_values_all') or not self.query_values_all:
            messagebox.showwarning('提示', '没有可查询的单号！')
            return
        if not messagebox.askyesno('确认', f'本次将查询 {len(self.query_values_all)} 条单号，是否继续？'):
            return
        self.query_values = self.query_values_all.copy()
        self.status_var.set(f"开始查询，共{len(self.query_values)}条...")
        self.log_text['state'] = 'normal'
        self.log_text.delete('1.0', tk.END)
        self.log_text['state'] = 'disabled'
        self.is_running = True
        self.query_btn['text'] = '停止查询'
        self.query_btn['state'] = 'normal'
        threading.Thread(target=self.run_tracking_crawler, daemon=True).start()
        self.after(500, self.update_progress_and_log, len(self.query_values))

    def update_progress_and_log(self, total):
        log_file = 'tracking_progress.log'
        log_lines = []
        if os.path.exists(log_file):
            with open(log_file, 'r', encoding='utf-8') as f:
                log_lines = f.readlines()
        # 只显示最新一条
        last_line = log_lines[-1] if log_lines else ''
        self.log_text['state'] = 'normal'
        self.log_text.delete('1.0', tk.END)
        self.log_text.insert(tk.END, last_line)
        self.log_text['state'] = 'disabled'
        completed = len(log_lines)
        if completed < total and self.is_running:
            self.status_var.set(f"正在查询... {completed}/{total}")
            self.after(500, self.update_progress_and_log, total)
        elif not self.is_running:
            self.status_var.set("查询已中断或完成。请查看结果文件夹。")
        else:
            self.status_var.set("查询完成！请查看结果文件夹。")
            self.refresh_output_stats()

    def run_tracking_crawler(self):
        try:
            import subprocess
            import sys
            import json
            temp_file = 'tracking_temp_list.json'
            with open(temp_file, 'w', encoding='utf-8') as f:
                json.dump(self.query_values, f, ensure_ascii=False)
            script_path = os.path.abspath('tracking_crawler.py')
            self.proc = subprocess.Popen([sys.executable, script_path, temp_file])
            self.proc.wait()
            os.remove(temp_file)
            self.is_running = False
            self.query_btn['state'] = 'normal'
            self.query_btn['text'] = '开始查询'
            self.status_var.set("查询完成！请查看结果文件夹。")
            self.refresh_output_stats()
        except Exception as e:
            self.status_var.set(f"查询出错: {e}")
            self.is_running = False
            self.query_btn['state'] = 'normal'
            self.query_btn['text'] = '开始查询'
            messagebox.showerror('错误', f'调用查询脚本失败：{e}')

    def stop_query(self):
        try:
            with open('tracking_stop.flag', 'w') as f:
                f.write('stop')
            self.status_var.set("已请求停止，等待子进程退出...")
            self.is_running = False
            self.query_btn['state'] = 'disabled'
        except Exception as e:
            messagebox.showerror('错误', f'停止失败: {e}')

    def refresh_output_stats(self):
        """刷新输出文件夹的分类和图片数量统计"""
        output_dir = 'tracking_screenshots'
        self.output_stats.clear()
        self.category_listbox.delete(0, tk.END)
        self.file_listbox.delete(0, tk.END)
        total_files = 0
        categories = []
        if os.path.exists(output_dir):
            for folder in os.listdir(output_dir):
                folder_path = os.path.join(output_dir, folder)
                if os.path.isdir(folder_path):
                    files = [f for f in os.listdir(folder_path) if f.lower().endswith('.png')]
                    self.output_stats[folder] = files
                    total_files += len(files)
                    display_name = f"{folder} ({len(files)})"
                    self.category_listbox.insert(tk.END, display_name)
                    categories.append(folder)
        self.total_label.config(text=f"总图片数: {total_files}")
        # 优先选中上次用户选中的分类
        selected_idx = 0
        if self.last_selected_category:
            for idx, folder in enumerate(categories):
                if folder == self.last_selected_category:
                    selected_idx = idx
                    break
        if self.category_listbox.size() > 0:
            self.category_listbox.selection_set(selected_idx)
            self.on_category_select()

    def on_category_select(self, event=None):
        selection = self.category_listbox.curselection()
        self.file_listbox.delete(0, tk.END)
        if selection:
            idx = selection[0]
            display_name = self.category_listbox.get(idx)
            category = display_name.split(' (')[0]
            self.last_selected_category = category  # 记录当前选中的分类
            files = self.output_stats.get(category, [])
            for f in files:
                self.file_listbox.insert(tk.END, f)

    def open_output_folder(self):
        import platform, subprocess
        output_dir = os.path.abspath('tracking_screenshots')
        try:
            if platform.system() == "Windows":
                os.startfile(output_dir)
            elif platform.system() == "Darwin":
                subprocess.run(["open", output_dir])
            else:
                subprocess.run(["xdg-open", output_dir])
        except Exception as e:
            messagebox.showerror("错误", f"打开文件夹失败: {e}") 